package com.uuuo.rxandroid;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;

import java.util.ArrayList;

import rx.Observable;
import rx.Observer;
import rx.Subscriber;
import rx.functions.Action1;
import rx.functions.Func1;

public class Main2Activity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);

    }

    public void subscribe(View view) {
        Observable<String> observable = Observable.create(new Observable.OnSubscribe<String>() {
            @Override
            public void call(Subscriber<? super String> subscriber) {
                subscriber.onNext("111111");
                subscriber.onNext("222222");
                subscriber.onNext("333333");
//                subscriber.onError(new NullPointerException());
                subscriber.onNext("444444");
                subscriber.onNext("555555");
                subscriber.onCompleted();
                subscriber.onNext("666666");
            }
        });

        Observer observer = new Observer<String>() {
            @Override
            public void onCompleted() {
                Commutils.Logi("onCompleted");
            }

            @Override
            public void onError(Throwable e) {
                e.printStackTrace();
            }

            @Override
            public void onNext(String s) {
                Commutils.Logi(s);
            }
        };

        observable.subscribe(observer);
    }

    public void map(View view) {
        ArrayList<Integer> intArrs = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            intArrs.add(i);
        }

        ArrayList<String> strArrs = new ArrayList<>();
        for (int i = 0; i < 6; i++) {
            strArrs.add("this is " + i);
        }

        final ArrayList<ArrayList> arr = new ArrayList();
        arr.add(intArrs);
        arr.add(strArrs);
        arr.add(intArrs);
        arr.add(strArrs);
        arr.add(intArrs);
        arr.add(strArrs);

        Observable.from(arr).switchMap(new Func1<ArrayList, Observable<ArrayList>>() {
            @Override
            public Observable<ArrayList> call(ArrayList arrayList) {
                return Observable.from(arrayList);
            }
        }).subscribe(new Action1<Object>() {
            @Override
            public void call(Object arrayList) {
                if (arrayList.toString().contains("3")){
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                Commutils.Logi(arrayList.toString());
            }
        });
    }
}
